package utils;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class CollectionUtils {
	/**
	 * Gets first or default element from given collection
	 * 
	 * @param source
	 * @return First element of collection (if not empty) or null otherwise
	 */
	public static <T> T first(Collection<T> source) {
		Iterator<T> iterator = source.iterator();
		if (iterator.hasNext()) {
			T first = iterator.next();
			return first;
		}

		return null;
	}

	/**
	 * Checks whether target list doesn't contain newValue and adds element
	 * 
	 * @param target
	 *            Target list
	 * @param newValue
	 *            Value to be added into target list
	 */
	public static <T> void addIfNotContains(List<T> target, T newValue) {
		if (target == null)
			return;

		if (target.contains(newValue))
			return;

		target.add(newValue);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> castList(@SuppressWarnings("rawtypes") List source) {
		return (List<T>) source;
	}

	public static <T> Stack<T> asStack(List<T> source) {
		Stack<T> result = new Stack<T>();

		if (source != null) {
			for (T s : source) {
				result.add(s);
			}
		}

		return result;
	}
}
